package br.com.Login.controller.filtros;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.Login.bean.Autorizacao;
import br.com.Login.bean.User;
import br.com.Login.controller.SessaoUserInterface;

public class FiltroNavegacao implements Filter{

	private List<String> str = new ArrayList<String>();

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String uri = httpRequest.getRequestURI().toString();

		try {
			SessaoUserInterface u = (SessaoUserInterface)Class.forName(request.getServletContext().getInitParameter("sessao_usuario")).newInstance();
			
			if(u != null && u.getUser().getUsername()!= null && verificaPermissao(u.getUser(), uri) == true){
				chain.doFilter(request, response);
			}else{
				HttpServletResponse hr = (HttpServletResponse)response;
				String context = httpRequest.getContextPath();
				hr.sendRedirect(context+"/pages/resourcePages/errorRedirectPermissao.xhtml");
			}
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}

	public Boolean verificaPermissao(User user, String url) {
		if(user.getAutorizacoes() == null || user.getAutorizacoes().size() <= 0){
			return false;
		}
		for (Autorizacao a : user.getAutorizacoes()) {

			str.add(a.getAutorizacao());
		}
		if(verifica(url) == true){
			return true;
		}else{
			return false;
		}

	}

	public Boolean verifica(String url) {
		if(str.contains(url)){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
}
